<?php

namespace App\Admin\Controllers;

use App\Admin\Filters\ConfigFilter;
use App\Admin\Requests\UpdateConfigValuesRequest;
use App\Admin\Requests\ConfigRequest;
use App\Admin\Resources\ConfigResource;
use App\Admin\Models\Config;
use App\Admin\Models\ConfigCategory;
use App\Admin\Models\VueRouter;
use App\Admin\Models\VueAdminUserRouter;
use App\Admin\Models\SystemModel;
use App\Admin\Utils\Admin;
use Illuminate\Support\Str;
use Illuminate\Support\Facades\Artisan;
use Illuminate\Support\Facades\Schema;

class ConfigController extends Controller
{
    public function vueRouters(VueRouter $vueRouter, VueAdminUserRouter $vueAdminUserRouter)
    {
        $vueRouterList = $vueRouter->treeWithAuth()->toTree();
        if (!Admin::isAdministrator()) {
            $vueAdminUserRouter->createVueAdminUserRouter($vueRouterList, Admin::user()->id);
            $vueRouterList = $vueAdminUserRouter->getVueAdminUserRouterList();
        } 
        return $this->ok($vueRouterList);
    }

    public function destroy(Config $config)
    {
        $config->delete();
        return $this->noContent();
    }

    public function edit(Config $config)
    {
        // 所有字段
        $config->configs = $config->configs($config->category_id);
        $validation_rules = explode('|', $config->validation_rules);
        foreach ($validation_rules as $key => $value) {
            $value2Arr = explode(":", $value);
            $validation_rules[$value2Arr[0]] = isset($value2Arr[1]) ? explode(",", $value2Arr[1]) : null;
            unset($validation_rules[$key]);
        }
        $formData = $this->formData();
        $maxCount = current($formData['validation_rules_map'])['count'];
        foreach ($formData['validation_rules_map'] as $key => $value) {
            // unique 验证规则默认参数
            if ($value['key']=='unique') {
                $value['params'] = [
                    [
                        'key'=>'table_name',
                        'value'=>null
                    ],
                    [
                        'key'=>'column_name',
                        'value'=>null
                    ]
                ];
            }
            // exists 验证规则默认参数
            if ($value['key']=='exists') {
                $value['params'] = [
                    [
                        'key'=>'table_name',
                        'value'=>null
                    ],
                    [
                        'key'=>'column_name',
                        'value'=>null
                    ]
                ];
            }
            // not_regex/regex 验证规则默认参数
            if ($value['key']=='not_regex' || $value['key']=='regex') {
                $value['params'] = [
                    [
                        'key'=>$value['key'],
                        'value'=>null
                    ]
                ];
            }
            // 已选择的排在最前面，count重新计算
            if (array_key_exists($value['key'], $validation_rules)) {
                $formData['validation_rules_map'][$key]['count'] = $maxCount+$value['count'];
            }
            $pv = $validation_rules[$value['key']] ?? null;
            foreach ($value['params'] as $key3 => $value3) {
                $formData['validation_rules_map'][$key]['param'.$key3.'_key'] = $value3['key'];
                $formData['validation_rules_map'][$key]['param'.$key3.'_value'] = $pv[$key3] ?? null;
            }
            unset($formData['validation_rules_map'][$key]['params']);
        }
        $formData['validation_rules_map'] = array_key_sort($formData['validation_rules_map'], 'count', SORT_DESC);
        return $this->ok(
            ConfigResource::make($config)
            ->for(ConfigResource::FOR_EDIT)
            ->additional($formData)
        );
    }

    public function update(ConfigRequest $request, Config $config)
    {
        $inputs = $request->validated();
        $inputs['value'] = $inputs['value'] ?? null;
        $config->update($inputs);
        return $this->created(
            ConfigResource::make($config)
        );
    }

    public function index(ConfigFilter $filter, Config $config)
    {
        $configs = Config::withTrashed(isRestore())
            ->filter($filter)
            ->orderByDesc('id')
            ->paginate();
        foreach ($configs as $key => $value) {
            if ($value['type'] == SystemModel::TYPE_DYNAMIC_INPUT || $value['type'] == SystemModel::TYPE_DYNAMIC_TEXTAREA) {
                isset($value['value']) && $configs[$key]['value'] = $config->formatValue($value['value']);
            }
        }

        return $this->ok(
            ConfigResource::forCollection(
                ConfigResource::FOR_INDEX, $configs
            )
        );
    }

    /**
     * 添加和编辑表单所需数据
     *
     * @return array
     */
    protected function formData()
    {
        $types_map = SystemModel::$inputTypeMap+SystemModel::$searchTypeMap;
        return [
            'types_map' => Config::typeMapSort($types_map),
            'categories' => ConfigCategory::query()
                ->orderByDesc('id')
                ->get(),
            'validation_rules_map' => Config::validationRuleMapSort(Config::validationRuleMap())
        ];
    }

    public function create()
    {
        return $this->ok($this->formData());
    }

    public function store(ConfigRequest $request)
    {
        $inputs = $request->validated();
        $inputs['value'] = $inputs['value'] ?? null;
        $config = Config::create($inputs);
        return $this->created(
            ConfigResource::make($config)
        );
    }

    public function updateValues(UpdateConfigValuesRequest $request)
    {
        $configs = $request->getConfigs();
        $configs = Config::updateValues($configs, $request->validated());
        return $this->created($configs);
    }

    public function getValuesByCategorySlug(VueAdminUserRouter $vueAdminUserRouter,string $categorySlug)
    {
        if (Admin::isAdministrator()) {
            return $this->ok(config(Config::CONFIG_KEY.'.'.$categorySlug), []);
        } else {
            $routeIdArr = $vueAdminUserRouter->getVueAdminUserRouterId(0);
            $config = config(Config::CONFIG_KEY.'.'.$categorySlug);
            if ($categorySlug=='system_basic' && $config['home_route'] && Admin::user()) {
                $home_route = Admin::user()->id.sprintf("%05d", $config['home_route']);
                if (in_array($home_route, $routeIdArr)) {
                    // 默认访问系统配置中的路由
                    $config['home_route'] = $home_route;
                } else {
                    // 如果系统配置中的路由不存在管理员路由中，默认访问第一个路由
                    $config['home_route'] = $routeIdArr[0];
                }
            }
            return $this->ok($config, []);
        }
    }

    public function cache()
    {
        Artisan::call('admin:cache-config');
        Artisan::call('cache:clear');
        Artisan::call('config:clear');
        Artisan::call('route:clear');
        Artisan::call('view:clear');
        Artisan::call('clear-compiled');
        return $this->noContent();
    }

    public function getInnerTitle()
    {
        $path = request()->input('path');
        $vueRouters = VueRouter::where('path','like',"%:id%")->get(['title','path']);
        $title = '';
        foreach ($vueRouters as $value) {
            $value['path'] = str_replace(':id', '', $value['path']);
            $pattern = '/\/'.str_replace('/', '\/', $value['path']).'/';
            if (preg_match($pattern, $path, $matches)) {
                $routerArr = explode('/', $matches[0]);
                $dummyResource = Str::camel(Str::singular($routerArr[1]));
                $ucDummyResource = Str::ucfirst($dummyResource);
                $ucDummyResource = "App\Admin\Models\\$ucDummyResource";
                $model = new $ucDummyResource;
                $tableName = $model->getTable();
                $id = $routerArr[2];
                if ($tableName=='system_models') {
                    $id = $model->whereId($id)->value('parent_id');
                } elseif ($tableName=='configs') {
                    $id = $model->whereId($id)->value('category_id');
                    $model = app(ConfigCategory::class);
                }
                if (Schema::hasColumn($tableName, 'name')) {
                    $title = $model->whereId($id)->value('name');
                } elseif (Schema::hasColumn($tableName, 'title')) {
                    $title = $model->whereId($id)->value('title');
                } else {
                    $title = $id;
                }
            }
        }
        return $this->ok(['title'=>$title]);
    }

    // 获取选项配置
    public function getSelectConfigs()
    {
        $re = Config::withTrashed(isRestore())
            ->whereIn('type',['single','multiple'])
            ->get(['id','name']);
        return $this->ok($re);
    }

    public function show(Int $id)
    {
        $adminUser = Config::withTrashed(isRestore())->find($id);
        return $this->ok(
            ConfigResource::make($adminUser) 
            ->for(ConfigResource::FOR_SHOW)     
        );
    }

    public function getByCategorySlug(string $categorySlug)
    {
        return $this->ok(
            ConfigResource::forCollection(
                ConfigResource::FOR_CONFIG, Config::getByCategorySlug($categorySlug)
            )
        );
    }
}
